import React, { Component, PropTypes } from 'react'
import moment from 'moment'
import {
  Tabs,
  Card,
  Tag,
  Button,
  Modal,
  Form,
  Input,
  message,
  Row,
  Col,
  Collapse,
  DatePicker,
  InputNumber,
  Radio
} from 'antd'
import { fetchPost } from '../../../../utils/request'
import Contacts from './info/Contacts'
import Relation from './info/Relation'
import ThirdContacts from './info/ThirdContacts'
import Styles from './Index.less'
import Records from '../../common/Record'
import BillDetail from '../../common/BillDetail'
import Info from './info/Info'
import BasicInfo from './info/BasicInfo'
import Profession from '../../../common/components/users/Profession'
import ClContact from './info/ClContact'
import LoanRecord from './info/LoanRecord.js'
import PaymentRecord from './info/PaymentRecord.js'
import PhoneRemarkRecord from '../../../common/components/users/PhoneRemarkRecord'
import CheckRecord from '../../../common/components/users/CheckRecord'
import Transfer from './info/Transfer'
import styles from '../Index.less'
import Images from "./info/Images";

const TabPane = Tabs.TabPane
const FormItem = Form.Item
const Panel = Collapse.Panel

class Detail extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      id: props.id,
      userId: props.userId,
      activeKey: props.activeKey,
      isNBFCAdmin: props.isNBFCAdmin,
      isAgentManager: props.isAgentManager,
      operateAllow: true,
      item: props.item,
      visible: false,
      orderStatus: props.orderStatus,
      tagId: null,
      tagData: [],
      conclusion: null,
      conclusionList: [],
      deductTypeList: [],
      reason: null,
      promiseTime: '',
      refreshOverdueRecord: false,
      refreshOrderFollow: false,
      activeRecord: '',
      recordRefresh: false,
      outerOverdue: false,
      collectionType: props.collectionType,
      phoneStatus: props.phoneStatus, //是否显示通讯录,
      sendMsgVisible: false,
      deductVisible: false,
      repaymentInfo: {},
    }
  }

  componentWillReceiveProps (props) {
    if (this.state.id != props.id || this.state.userId != props.userId ||
      this.state.orderStatus != props.orderStatus || this.state.phoneStatus != props.phoneStatus
      || this.state.operateAllow != props.operateAllow
      || this.state.isAgentManager != props.isAgentManager) {
      this.setState({
        id: props.id,
        activeKey: props.activeKey,
        userId: props.userId,
        orderStatus: props.orderStatus,
        item: props.item,
        phoneStatus: props.phoneStatus,
        operateAllow: props.operateAllow,
        isAgentManager: props.isAgentManager,
      })
    }
  }

  componentDidMount () {
    this.getData()
  }

  getData () {
    fetchPost('/collection/v2/case/query').then(res => {
      if (res.code === 0) {
        this.setState({
          tagData: res.data.tagDataList,
          conclusionList: res.data.conclusionList,
          deductTypeList: res.data.deductTypeList,
        })
      }
    })
  }

  onChange (activeKey) {
    this.setState({ activeKey })
  }

  handleModalOk () {
    let self = this
    if (this.state.tagId == null) {
      message.warning('Please choose the order status tag')
      return false
    }

    let data = {
      type: this.state.tagId,
      content: this.props.form.getFieldValue('statusDescription'),
      collectionNo: this.state.item.collectionNo,
      tradeNo: this.state.item.tradeNo,
      userCode: this.state.item.userCode,
      name: this.state.item.name,
      mobile: this.state.item.mobile,
      followId: this.state.item.followId,
      followUp: this.state.item.followUp,
    }

    if (this.state.tagId == 7) {
      if (this.state.promiseTime == '') {
        message.warning('Please choose the promise time')
        return false
      } else {
        data.promisePayDate = this.state.promiseTime
      }
    }

    fetchPost('/collection/v2/comment/add', data).then(data => {
      if (data.code === 0) {
        this.changeModal()
        this.props.form.resetFields()
        this.props.refreshList()
        this.setState({
          refreshOrderFollow: true,
        }, () => {
          self.setState({
            refreshOrderFollow: false,
          })
        })
        message.success('Operation success')
      } else {
        message.error(data.msg)
      }
    })
  }

  changeModal () {
    this.props.form.resetFields()
    this.setState({
      visible: !this.state.visible,
      tagId: null,
      conclusion: null,
      promiseTime: '',
      reason: null,
    })
  }

  getColor (tagId) {
    if (this.state.tagId == tagId) {
      return '#87d068'
    }
  }

  chooseTag (value) {
    this.setState({
      tagId: value.value,
      reason: `[${value.name}]`
    })
  }

  getConclusionColor (conclusion) {
    if (this.state.conclusion == conclusion) {
      return '#87d068'
    }
  }

  chooseConclusion (value) {
    this.setState({
      conclusion: value.type
    })
  }

  extraContent () {
    // NBFC管理员不可以点击
    if (this.props.isNBFCAdmin) {
      return (
        <div>
          <Button type='primary' disabled={true}>Operate</Button>
        </div>
      )
    }
    if (this.state.operateAllow) {
      if (this.state.isAgentManager) {
        return <div>
          <Row>
            <Col span={10}></Col>
            <Col span={4}>
              <Button style={{ marginRight: 10 }} type='primary'
                      onClick={() => this.getDeductPaybackItem()}>Deduction</Button>
            </Col>
            <Col span={6}>
              <Button disabled={true} style={{ marginRight: 10 }} type='primary'
                      onClick={() => this.getPaybackItem()}>Send Repay Links</Button>
            </Col>
            {/*<Col span={4}>*/}
            {/*  <Button style={{marginRight: 10}} type='primary'*/}
            {/*          onClick={() => this.showTransferModal()}>Transfer</Button>*/}
            {/*</Col>*/}
            <Col span={4}>
              <Button type='primary' onClick={this.changeModal.bind(this)}>Operate</Button>
            </Col>
          </Row>
        </div>
      } else {
        return <div>
          <Row>
            <Col span={14}> </Col>
            <Col span={6}>
              <Button style={{ marginRight: 10 }} type='primary' disabled={true}
                      onClick={() => this.getPaybackItem()}>Send Repay Links</Button>
            </Col>
            {/*<Col span={4}>*/}
            {/*  <Button style={{marginRight: 10}} type='primary'*/}
            {/*          onClick={() => this.showTransferModal()}>Transfer</Button>*/}
            {/*</Col>*/}
            <Col span={4}>
              <Button type='primary' onClick={this.changeModal.bind(this)}>Operate</Button>
            </Col>
          </Row>
        </div>
      }
    } else {
      return <div></div>
    }
  }

  refreshOverdueRecord () {
    let self = this
    this.setState({
      refreshOverdueRecord: true,
    }, () => {
      self.setState({
        refreshOverdueRecord: false,
      })
    })
  }

  recordRefresh () {
    this.setState({
      recordRefresh: true,
    })
  }

  handleChange (value) {
    this.setState({
      content: value
    }, () => {
      console.log(this.state.content)
    })
  }

  showTransferModal (record) {
    this.setState({
      transferVisible: true,
    })

  };

  handleTransferOk = e => {
    this.getData()
    this.props.refreshList()
    this.setState({
      transferVisible: false,
    })
  }

  handleTransferCancel = e => {
    this.setState({
      transferVisible: false,
    })
  }

  handleSendMsgOk = e => {
    let self = this
    this.props.form.validateFields((error) => {
      if (!error) {
        const { paidCapital, sendWay, textType } = this.props.form.getFieldsValue()
        let billNo = this.state.repaymentInfo.billNo

        fetchPost(`/liquidation/repay/links/send`, { billNo, paidCapital, sendWay, textType }).then((res) => {
          if (res.code === 0) {
            self.props.form.resetFields()
            this.setState({
              sendMsgVisible: false,
            })
            Modal.success({
              title: 'RepaymentLink',
              content: (
                <div>
                  <h1>{res.data.shortLinks}</h1>
                </div>
              ),
            })
          } else {
            message.error(res.msg)
          }
        })
      }
    })
  }

  handleSendMsgCancel = e => {
    this.props.form.resetFields()
    this.setState({
      sendMsgVisible: false,
    })
  }

  handleDeductOk () {
    let self = this
    const { deductType } = this.props.form.getFieldsValue()
    let billNo = this.state.repaymentInfo.billNo
    let tradeNo = this.state.repaymentInfo.orderNo
    fetchPost(`/liquidation/deduct/submit`, { tradeNo, billNo, deductType }).then((res) => {
      if (res.code === 0) {
        self.props.form.resetFields()
        this.setState({
          deductVisible: false,
        })
        if (res.data && res.data.shortLinks && res.data.shortLinks.length > 0) {
          Modal.success({
            title: 'RepaymentLink',
            content: (
              <div>
                <h1>{res.data.shortLinks}</h1>
              </div>
            ),
          })
        }
      } else {
        message.error(res.msg)
      }
    })
  }

  handleDeductCancel = e => {
    this.props.form.resetFields()
    this.setState({
      deductVisible: false,
    })
  }

  getPaybackItem () {
    let time = moment().format('YYYY-MM-DD')
    fetchPost(`/liquidation/v2/${this.state.item.tradeNo}/repayment/info?paymentDt=${time}`).then((res) => {
      if (res.code === 0) {
        this.setState({
          repaymentInfo: res.data.repaymentInfo,
          sendMsgVisible: true
        }, () => {
          this.props.form.setFieldsValue({
            'paidCapital': res.data.repaymentInfo.remainCapital
          })
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  getDeductPaybackItem () {
    let time = moment().format('YYYY-MM-DD')
    fetchPost(`/liquidation/v2/${this.state.item.tradeNo}/repayment/info?paymentDt=${time}`).then((res) => {
      if (res.code === 0) {
        this.setState({
          repaymentInfo: res.data.repaymentInfo,
          deductVisible: true
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  /**
   * 展示还款信息
   */
  showRepaymentInfo () {
    //已经结清
    if (this.state.repaymentInfo.billStatus === 2) {
      return (<div>
        <p className='font14 mt10'>Repayment Channel: {this.state.repaymentInfo.repaymentChannel}</p>
        <p className='font14 mt10'>Transaction Number: {this.state.repaymentInfo.transactionNumber}</p>
        <p className='font14 mt10'>Repayment Date: {this.state.repaymentInfo.repaymentDate}</p>
      </div>)
    } else {
      const { getFieldDecorator } = this.props.form

      const formItemLayout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      }

      return (
        <div>
          <FormItem className='mt20' label='Text:' {...formItemLayout}>
            {
              getFieldDecorator('textType', {
                initialValue: '1',
                rules: [{
                  required: true,
                  message: 'Please enter the text'
                }]
              })(
                <Radio.Group>
                  <Radio value='1' className={Styles.contentRadio}>
                    Dear ##name##, please repay your loan in ##AppName##, you can pay quickly through the following
                    payment link: ##links##
                  </Radio>
                </Radio.Group>
              )
            }
          </FormItem>
          <FormItem className='mt20' label='Inform the way:' {...formItemLayout}>
            {
              getFieldDecorator('sendWay', {
                initialValue: 'all',
                rules: [{
                  required: true,
                  message: 'Please enter the inform way'
                }]
              })(
                <Radio.Group>
                  <Radio value='all'>All</Radio>
                  <Radio value='sms'>SMS</Radio>
                  <Radio value='email'>E-mail</Radio>
                </Radio.Group>
              )
            }
          </FormItem>
          <FormItem className='mt20' label='Repayment Amount:' {...formItemLayout}>
            {
              getFieldDecorator('paidCapital', {
                rules: [{
                  required: true,
                  message: 'Please enter the amount of repayment'
                }, { pattern: /^[0-9]*\.?[0-9]{0,2}$/, message: 'Please enter the correct format' }]
              })(
                <Input type='text'/>
              )
            }
          </FormItem>

          {/*<FormItem className='mt20' label='Set the links duration:' {...formItemLayout}>*/}
          {/*  {*/}
          {/*    getFieldDecorator('validTime', {*/}
          {/*      initialValue: 24,*/}
          {/*      rules: [{*/}
          {/*        required: true,*/}
          {/*        message: 'Please enter the links valid time'*/}
          {/*      }, {pattern: /^[0-9]*\.?[0-9]{0,2}$/, message: 'Please enter the correct format'}]*/}
          {/*    })(*/}
          {/*      <InputNumber min={1} max={72}/>*/}
          {/*    )*/}
          {/*  }*/}
          {/*</FormItem>*/}
        </div>
      )
    }
  }

  showRepaymentLink () {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    }
    if (this.state.shortLinks) {
      return (
        <div>
          <FormItem className='mt20' label='Repayment Link:' {...formItemLayout}>
            <Input type='text' value={this.state.shortLinks}/>
          </FormItem>
        </div>
      )
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form
    return (
      <div>
        <Modal visible={this.state.visible}
               onOk={this.handleModalOk.bind(this)}
               onCancel={this.changeModal.bind(this)}
        >
          <Form>

            <FormItem>
              <div><strong>Status list: </strong></div>
              <div>
                {
                  this.state.tagData.map((value, index) => (
                    <Tag key={index} onClick={(e) => this.chooseTag(value)}
                         color={this.getColor(value.value)}>{value.name}</Tag>
                  ))
                }
              </div>

              {
                this.state.tagId !== null && this.state.tagId == 6
                  ? <div>Promise Date：<DatePicker
                    showTime
                    format='YYYY-MM-DD HH:MM:SS'
                    placeholder='End time'
                    onChange={(value, dateString) =>
                      this.setState({
                        promiseTime: dateString,
                      })
                    }
                  /></div> : ''
              }

            </FormItem>

            <FormItem>
              {getFieldDecorator('statusDescription', { initialValue: this.state.reason })(
                <Input placeholder='Please enter the reason' className='mh150' type='textarea'/>,
              )}
            </FormItem>
          </Form>
        </Modal>
        <div className={Styles.hideScroll}>
          {this.extraContent()}
          <Card bodyStyle={{ padding: 0 }} bordered={false} noHovering={true}>
            <div className=''>
              <Tabs className={Styles.tabs} activeKey={this.state.activeKey}
                    onChange={(e) => this.onChange(e)}>

                <TabPane tab='Basic-Info' key='baseInfo'>
                  {
                    this.state.activeKey === 'baseInfo'
                      ? <div className={Styles.tabsWrapper}>
                        <div className='clearfix'>
                          <Col span={24}>
                            <BillDetail item={this.state.item}
                                        userId={this.state.userId}
                                        id={this.state.id}
                            />
                          </Col>
                        </div>
                        <div>
                          <Info userId={this.state.userId} tradeNo={this.state.item.tradeNo}/>
                        </div>
                        <div>
                          <Tabs onChange={this.callback} type="line">
                            <TabPane tab="BASIC" key="1">
                              <BasicInfo userId={this.state.userId} tradeNo={this.state.userId}
                                         stepType={this.state.stepType}/>
                            </TabPane>
                            {/*<TabPane tab="WORKING" key="2">*/}
                            {/*  <Profession orderId={this.state.id} userId={this.state.userId}/>*/}
                            {/*</TabPane>*/}
                            {
                              this.state.processNode == '1' ? null
                                :
                                <TabPane tab="CONTACT" key="3">
                                  <ClContact id={this.state.id} userId={this.state.userId} tradeNo={this.state.userId}/>
                                </TabPane>
                            }
                          </Tabs>
                        </div>
                      <Images collectionNo={this.state.item.collectionNo}/>
                      </div> : null
                  }
                </TabPane>

                {
                  this.state.phoneStatus
                    ? <TabPane tab='Contact' key='contacts'>
                      {
                        this.state.activeKey === 'contacts'
                          ? <div className={Styles.tabsWrapper}>
                            <Relation userId={this.state.userId} id={this.state.id} item={this.state.item}/>
                            {/*<ThirdContacts changeModal={() => this.changeModal()} tradeNo={this.state.userId}*/}
                            {/*               id={this.state.id} item={this.state.item}/>*/}
                            <Contacts
                              collectionType={this.state.collectionType}
                              recordRefresh={() => this.recordRefresh()}
                              activeRecord={this.state.activeRecord}
                              showCalls={false}
                              refreshOverdueRecord={() => {
                                this.refreshOverdueRecord()
                              }}
                              outCallDo={(phone) => this.props.outCallDo(phone)}
                              id={this.state.id}
                              item={this.state.item}
                              isNBFCAdmin={this.props.isNBFCAdmin}
                              userId={this.state.userId}/>
                            <div>
                              <Records userId={this.state.userId}
                                       refreshOverdueRecord={this.state.refreshOverdueRecord}
                                       recordRefresh={() => this.recordRefresh()}
                                       refresh={this.state.recordRefresh}
                                       outerOverdue={this.state.outerOverdue}
                                       isShowXZCJ
                                       item={this.state.item}
                                       isNBFCAdmin={this.props.isNBFCAdmin}
                              />
                            </div>

                          </div> : null
                      }
                    </TabPane>
                    : ''
                }
                <TabPane tab='Follow Up Record' key='followUp'>
                  <Records userId={this.state.userId}
                           refreshOverdueRecord={this.state.refreshOverdueRecord}
                           recordRefresh={() => this.recordRefresh()}
                           refresh={this.state.recordRefresh}
                           outerOverdue={this.state.outerOverdue}
                           isShowXZCJ
                           item={this.state.item}
                           isNBFCAdmin={this.props.isNBFCAdmin}
                  />
                </TabPane>
                {/*<TabPane tab='Application History' key='records'>*/}
                {/*  {*/}
                {/*    this.state.activeKey === 'records' ?*/}
                {/*      <div className={Styles.tabsWrapper}>*/}
                {/*        <LoanRecord userId={this.state.userId}/>*/}
                {/*        <PaymentRecord tradeNo={this.state.userId}/>*/}
                {/*        <PhoneRemarkRecord userId={this.state.userId}/>*/}
                {/*        <CheckRecord userId={this.state.userId} tradeNo={this.state.userId}/>*/}
                {/*      </div>*/}
                {/*      : <span/>*/}
                {/*  }*/}
                {/*</TabPane>*/}
              </Tabs>
            </div>
          </Card>
        </div>
        <Modal
          title="Transfer"
          visible={this.state.transferVisible}
          onCancel={this.handleTransferCancel}
          footer={null}
        >
          <Transfer onOk={this.handleTransferOk} info={this.state.item}/>
        </Modal>

        <Modal
          title="Send SMS - Please enter the expected amount"
          visible={this.state.sendMsgVisible}
          okText={this.state.repaymentInfo.billStatus === 2 ? 'Cancel' : 'Send'}
          onOk={() => {
            this.handleSendMsgOk()
          }}
          onCancel={() => {
            this.handleSendMsgCancel()
          }}>
          <Form className={Styles.formWrapper}>
            <div className={Styles.info}>
              <div className={Styles.wrapper}>
                <Row gutter={8}>
                  <Col span={24} className='font14 mt10'>
                    Loan ID:{this.state.repaymentInfo.orderNo}
                  </Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Repayment
                    Amount: {this.state.repaymentInfo.repaymentCapital}</Col>
                  <Col span={12} className='font14 mt10'> Loan Amount: {this.state.repaymentInfo.borrowCapital}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Deductible
                    Amount: {this.state.repaymentInfo.discountCapital}</Col>
                  <Col span={12} className='font14 mt10'> Tenure: {this.state.repaymentInfo.periodLength}Days</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Overdue
                    Days: {this.state.repaymentInfo.overdueDays}Days</Col>
                  <Col span={12} className='font14 mt10'> Interest: {this.state.repaymentInfo.interest}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Processing
                    Fee: {this.state.repaymentInfo.serviceFee}</Col>
                  <Col span={12} className='font14 mt10'> Overdue Service
                    Fee: {this.state.repaymentInfo.overdueServiceFee}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Total
                    Penalty: {this.state.repaymentInfo.overdueFee}</Col>
                  <Col span={12} className='font14 mt10'> Penalty Per
                    Day: {this.state.repaymentInfo.borrowCapital * 0.01}</Col>
                </Row>

                <Col span={24} className='font14 color-main mt10'>
                  Remaining Repayment Amount: {this.state.repaymentInfo.remainCapital}
                </Col>
              </div>
              {this.showRepaymentInfo()}
              {this.showRepaymentLink()}
            </div>

          </Form>

        </Modal>

        <Modal
          title="Interest reduction"
          visible={this.state.deductVisible}
          okText={this.state.repaymentInfo.billStatus === 2 ? 'Cancel' : 'Send'}
          onOk={() => {
            this.handleDeductOk()
          }}
          onCancel={() => {
            this.handleDeductCancel()
          }}>
          <Form className={Styles.formWrapper}>
            <div className={Styles.info}>
              <div className={Styles.wrapper}>
                <Row gutter={8}>
                  <Col span={24} className='font14 mt10'>
                    Loan ID:{this.state.repaymentInfo.orderNo}
                  </Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Repayment
                    Amount: {this.state.repaymentInfo.repaymentCapital}</Col>
                  <Col span={12} className='font14 mt10'> Loan Amount: {this.state.repaymentInfo.borrowCapital}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Deductible
                    Amount: {this.state.repaymentInfo.discountCapital}</Col>
                  <Col span={12} className='font14 mt10'> Tenure: {this.state.repaymentInfo.periodLength}Days</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Overdue
                    Days: {this.state.repaymentInfo.overdueDays}Days</Col>
                  <Col span={12} className='font14 mt10'> Interest: {this.state.repaymentInfo.interest}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Processing
                    Fee: {this.state.repaymentInfo.serviceFee}</Col>
                  <Col span={12} className='font14 mt10'> Overdue Service
                    Fee: {this.state.repaymentInfo.overdueServiceFee}</Col>
                </Row>
                <Row gutter={8}>
                  <Col span={12} className='font14 mt10'> Total
                    Penalty: {this.state.repaymentInfo.overdueFee}</Col>
                  <Col span={12} className='font14 mt10'> Penalty Per
                    Day: {this.state.repaymentInfo.borrowCapital * 0.01}</Col>
                </Row>

                <Col span={24} className='font14 color-main mt10'>
                  Remaining Repayment Amount: {this.state.repaymentInfo.remainCapital}
                </Col>
              </div>
              <div>
                <FormItem className='mt20' label='Deduct Type:' labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                  {
                    getFieldDecorator('deductType', {
                      initialValue: '5',
                      rules: [{
                        required: true,
                        message: 'Please enter the deduct type'
                      }]
                    })(
                      <Radio.Group>
                        {
                          this.state.deductTypeList.map((val, index) => {
                            return (<Radio value={val.value}>{val.name}</Radio>)
                          })
                        }
                      </Radio.Group>
                    )
                  }
                </FormItem>
              </div>
            </div>

          </Form>

        </Modal>
      </div>
    )
  }
}

Detail = Form.create()(Detail)

export default Detail
